package com.example.musiccommunity.ManagerPage;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.aip.util.Base64Util;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.R;
import com.example.musiccommunity.util.ImageUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AddNews extends AppCompatActivity {
    private Toolbar toolbar;
    private ImageView img;
    private EditText author;
    private EditText title;
    private EditText addContent;
    private Button ok;


    private Bitmap bp = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_news);

        toolbar = findViewById(R.id.toolbar);
        img = findViewById(R.id.img);
        author = findViewById(R.id.author);
        title = findViewById(R.id.title);
        addContent = findViewById(R.id.add_content);
        ok = findViewById(R.id.ok);
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        BitmapDrawable bd = (BitmapDrawable) img.getDrawable();
        bp = bd.getBitmap();

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, 1);
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(addContent.getText().toString().equals("") ||author.getText().toString().equals("")
                        ||title.getText().toString().equals("")){
                    Toast.makeText(AddNews.this, "请填写完整", Toast.LENGTH_SHORT).show();
                    return ;
                }
                reqString();
            }
        });


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri u = data.getData();
            ContentResolver cr = AddNews.this.getContentResolver();
            try {
                Bitmap bit = BitmapFactory.decodeStream(cr.openInputStream(u));
                BitmapDrawable bd=new BitmapDrawable(bit);
                img.setImageDrawable(bd);
                new Thread(() -> {
                    bp= ImageUtil.compressImage(bd.getBitmap());
                    new Handler(Looper.getMainLooper()).post(() -> {
                    });
                }).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    void reqString(){
        byte[] bytes1 = ImageUtil.getBytesByBitmap(bp);
        String image1 = Base64Util.encode(bytes1);
        String url= MainActivity.ip+"/news/add";
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // 处理响应
                        String s=response;
                        Log.d("***********",s.toString());
                        if(s.toString().equals("success")){
                            Toast.makeText(AddNews.this, "新增成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }else{
                            Toast.makeText(AddNews.this, "图片过大!", Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 处理错误
                        Log.d("--------",error.getMessage().toString());
                        Toast.makeText(AddNews.this, "新增失败", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("author", author.getText().toString());
                params.put("title", title.getText().toString());
                params.put("txt",addContent.getText().toString());
                params.put("time", formatter.format(date));
                params.put("avatarBase64", image1); // 将 Base64 字符串作为参数传递
                return params;
            }
        };
        MainActivity.requestQueue.add(stringRequest);


    }
}